#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

int main() {
	int listener = socket(AF_INET, SOCK_DGRAM, 0);
	if (listener < 0) {
		perror("socket");
		exit(errno);
	}
	
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(2345);
	addr.sin_addr.s_addr = INADDR_ANY;
	if (bind(listener, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		perror("bind");
		exit(errno);
	}
	struct sockaddr from_addr;
	int addr_len = sizeof(from_addr);
	char buf[1024];
	printf("Server started.\n");
	while (1) {
		int bytes_read = recvfrom(listener, (void *)buf, 1024, 0, &from_addr, (socklen_t*)&addr_len);
		if (bytes_read < 0) {
			perror("read");
			exit(errno);	
		}
		printf("Server: %s\n", buf);
		int bytes_sent = sendto(listener, (void *)buf, sizeof(buf), 0, &from_addr, (socklen_t)addr_len);
	}
	close(listener);
	printf("Server stopped.\n");
	return 0;
}
